#pragma once

#include <iostream>
#include <map>
#include <unordered_map>
#include <string>
#include <fstream>
#include "Log.hpp"

const std::string defaultpath = "./dict.txt";
const std::string sep = ": ";

// 实现一个字典查找模块
class Dict
{
private:
	bool Load()
	{
		// 先打开文件流
		std::fstream in(_dict_conf_filepath);
		if (!in.is_open())
		{
			LOG(FATAL, "open %s error\n", _dict_conf_filepath.c_str());
			return false;
		}
		// 每次循环获取一行数据
		std::string line;
		while (std::getline(in, line))
		{
			if (line.empty()) // 处理空行情况
			{
				continue;
			}
			auto pos = line.find(sep);
			if (pos == std::string::npos)
				continue; // 处理格式异常问题
			std::string english = line.substr(0, pos);
			if (english.empty())
				continue; // 处理格式异常问题
			std::string chinese = line.substr(pos + sep.size());
			if (chinese.empty())
				continue;
			LOG(DEBUG, "load info, %s: %s\n", english.c_str(), chinese.c_str());

			// 存放到哈希表中，也就是加载到内存
			_dict.insert(std::make_pair(english, chinese));
		}

		in.close();
		LOG(DEBUG, "load %s success\n", _dict_conf_filepath.c_str());
		return true;
	}

public:
	Dict(std::string dict_conf_filepath = defaultpath) : _dict_conf_filepath(dict_conf_filepath)
	{
		// 把配置文件加载到内存中
		Load();
	}

	// 查找翻译功能
	std::string Translate(const std::string &word, bool &ok)
	{
		ok = true;
		auto iter = _dict.find(word);
		if (iter == _dict.end()) // 没找到的情况
		{
			ok = false;
			return "查无此词";
		}

		
		return iter->second;
	}

	~Dict()
	{
	}

private:
	std::unordered_map<std::string, std::string> _dict; // 用无排序哈希表来存放
	std::string _dict_conf_filepath;					// 配置文件路径
};